package letcode.commonOrder.$2$add_two_numbers;

import letcode.util.ListNode;

/**
 * @Description: 两数之和初始尝试
 * @Date: 2020/2/17
 * @Author: 许群星
 */
public class AddTwoNumbers {
    public static void main(String[] args) {
        //342
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        //465
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        //TODO:代码具体的实现与展示仍待实现
        AddTwoNumbers test=new AddTwoNumbers();
        ListNode sum=test.addTwoNumbers(l1,l2);
        System.out.println(sum.val);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //生成ListNode链表对象，链表的值为0，没有指向的节点
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        //两个链表的同一位赋值给变量x.y
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10; //这里的carry循环时在上面这个式子用int sum = carry + x + y
            curr.next = new ListNode(sum % 10);//如果结果是两位数，个位数留在结果链表里

            curr = curr.next;
            if (p != null) {
                p = p.next;
            }
            if (q != null) {
                q = q.next;
            }
        }
        //最后一位的进位，如果有进位，就把进位放到下一个链表里
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}


//    @Override
//    public String toString(){
//        final StringBuffer stringBuffer=new StringBuffer("ListNode{");
//        stringBuffer.append("val=").append(val);
//        stringBuffer.append(",next=").append(next);
//        stringBuffer.append("}");
//        return stringBuffer.toString();
//    }

/**
 * 自己对链表不太熟悉，所以暂定看链表知识，实在不会可以照着答案先去做，
 */